/**
 * 前端利用canvas压缩图片的工具
 */
const URL = window.URL;

if (!HTMLCanvasElement.prototype.toBlob) {
	Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
		value(callback, type, quality) {
			const binStr = atob(this.toDataURL(type, quality).split(',')[1]);
			const len = binStr.length;
			const arr = new Uint8Array(len);

			for (let i = 0; i < len; i++) {
				arr[i] = binStr.charCodeAt(i);
			}

			callback(new Blob([arr], { type: type || 'image/png' }));
		}
	});
}

export default function compression(file, opt = { width: 720, mimeType: 'image/png', quality: 0.8 }) {
	let url = '';
	if (typeof file === 'string') {
		url = file;
	} else url = URL.createObjectURL(file);

	return new Promise((res, ret) => {
		const img = document.createElement('img');
		img.onload = function () {
			let width = opt.width;
			let height = 0;
			if (img.width > width) {
				height = width / img.width * img.height;
			} else {
				width = img.width;
				height = img.height;
			}

			const r = 1;
			const canvas = document.createElement('canvas');
			canvas.style.display = 'none';
			canvas.width = width;
			canvas.height = height;
			document.body.appendChild(canvas);
			const ctx = canvas.getContext('2d');
			ctx.drawImage(img, 0, 0, img.width * r, img.height * r, 0, 0, width, height);
			canvas.toBlob(b => {
				// document.body.removeChild(img);
				// document.body.removeChild(canvas);
				res(b);
			}, opt.mimeType, opt.quality);
		};
		img.onerror = ret;
		img.src = url;
		img.style.display = 'none';
		document.body.appendChild(img);
	});
}
